var globals;
var INWARD="ORG"; 
var OUTWARD="DES";
var direction; 
var selected=9999999999999;

function doPost(r,direction)
{
	$.mobile.showPageLoadingMsg("b", "Refreshing...");
	
	$.ajax({url: r,data: { name: "John", time: "2pm" },dataType:"text"} )
	.done(function( text) {
	
	if(direction==INWARD){
	localStorage.arrivals=text;
	}
	if(direction==OUTWARD)
	{
	localStorage.departures=text;
	}
	processMovieTypes(text,direction);
	$.mobile.hidePageLoadingMsg();
	})
	.fail(function( jqxhr, textStatus, error ) {
	var err = textStatus + ', ' + error;
	console.log( "Request Failed: " + err);
	// show error message
	$.mobile.showPageLoadingMsg( $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true );
	
	// hide after delay
	setTimeout( $.mobile.hidePageLoadingMsg, 1500 );
	});
	
	
	
	
}




function javaUtilPut(arr,value)
{
      if(-1<iscityexist(value,arr)){
      
      arr.push(value);
      
      }

return arr;

}

function flightUtilPut(arr,maingroup,value,object)
{

      var arrayPosition=iscityexist(value,arr);
     
      if(arrayPosition==-1){
      
      arr.push(value);
      var detail={"city":value,"schedules":[]};
      maingroup.push(detail);
      maingroup[maingroup.length-1].schedules.push(object);
      }else{
      
      maingroup[arrayPosition].schedules.push(object);
      
      }
      
   


}
function setValuesToForm(sel,header)
{
selected=sel;
 $("#flight_d").text(globals[selected].flightNo);
$("#flight_d").text(globals[selected].flightNo);
$("#origin_d").text(globals[selected].origin);
$("#arrival_d").text(globals[selected].arrival);
$("#status_d").html(globals[selected].status);
$("#detailHeader").html(globals[selected].flightNo);
$("#header_1_d").text(header);

$("#selectedLogo").html('<img src="images/'+globals[selected].flightNo.substring(0,2)+'.gif" />');
localStorage.flightNumber=globals[selected].flightNo;

if(header=="Destination")
{
   $("#header_2_d").text("Departure Time");
 $("#arrival_d").prev('b').text('Departure Time');
$("#origin_d").prev('b').text('Destination');
}
if(header=="Origin")
{
   $("#header_2_d").text("Arrival Time");
 $("#arrival_d").prev('b').text('Arrival Time');
$("#origin_d").prev('b').text('Origin');
}

     

$("#positionMap").html("");
$.getJSON( "http://code.whereismyanmar.net/map/",{"flight":localStorage.flightNumber,"reverse":localStorage.direction})
.done(function(data) {

if(data.TrackLogResult!=undefined){
flightPlanCoordinates = [];

var logs=data.TrackLogResult.positions;


 for(var i=0;i<logs.length;i++)
{
   flightPlanCoordinates.push(new google.maps.LatLng(logs[i].latitude,logs[i].longitude));
} 
 
loadGoogleMap(flightPlanCoordinates,data);
}
else{
flightPlanCoordinates = [];
data={};
}
})
.fail(function( jqxhr, textStatus, error ) {
alert(error);
});


}
function loadGoogleMap(_flightPlanCoordinates,gdata)
{

if(flightPlanCoordinates==undefined || flightPlanCoordinates.length==0)
{
   return false;
} 
$('#mapcontainer').height('350px');
 $('#positionMap').height('350px');
$('#positionMap').gmap('destroy');
var flightPath = new google.maps.Polyline({
path: _flightPlanCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
}); 

$(function() { 
				
					$('#positionMap').gmap({'mapTypeId': google.maps.MapTypeId.HYBRID,'center': _flightPlanCoordinates[_flightPlanCoordinates.length-1], 'zoom': 7, 'disableDefaultUI':true, 'callback': function() {
						var self = this;
						self.addMarker({'position': _flightPlanCoordinates[_flightPlanCoordinates.length-1], icon:gdata.TrackLogResult.positions[_flightPlanCoordinates.length-1].direction+'.png' }).click(function() {
							self.openInfoWindow({ 'content': '<font style="color:green">'+globals[selected].flightNo+'</font>'}, this);
						});	
					}});

				
$('#positionMap').gmap('addShape', 'Polyline', { 'path': _flightPlanCoordinates, 'strokeOpacity': 0.8, 'strokeWeight': 2, 'strokeColor': '#FF0000' });
//$('#positionMap').gmap('addMarker', { /*id:'m_1',*/ 'position': '42.345573,-71.098326', 'bounds': true } );
			});



}
function iscityexist(value,arr)
{
   for(var i=0;i<arr.length;i++)
   {
   
       if(arr[i]==value)
       {
          return i;
       }
   
   
   }
   return -1;
}
   var zoomlevel=9;

    

      function initialize() {

    	var myLatlng=new google.maps.LatLng(18.3802680969238281,94.3356);

        var mapOptions = {

          center: myLatlng,

          zoom: zoomlevel,

          mapTypeId: google.maps.MapTypeId.ROADMAP

        };

        var map = new google.maps.Map(document.getElementById("track"),

            mapOptions);

        

  

        

        google.maps.event.addListener(map, 'click', function(event) {

        	//alert(event.latLng);

            placeMarker(event.latLng);

          });




var image='bullet_red.ico';  


    var flightPlanCoordinates = [];

$.getJSON( "http://code.whereismyanmar.net")
.done(function( data) {
	var logs=data.TrackLogResult.positions;
	for(var i=0;i<logs.length;i++)
	{
	  flightPlanCoordinates.push(new google.maps.LatLng(logs[i].latitude,logs[i].longitude)); 
	
	}
	
	
	  var flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
  });
    map.setCenter(flightPlanCoordinates[flightPlanCoordinates.length-1]);
    
          var marker = new google.maps.Marker({
            position: flightPlanCoordinates[flightPlanCoordinates.length-1],
            map: map,
            title:"current position" ,
            icon:image
        });
  flightPath.setMap(map);
  		
})
.fail(function( jqxhr, textStatus, error ) {
 //   alert(error);
});
   

      }
      
function processMovieTypes(text,direction){



if (text==undefined) return false;
var label_1="ETA";
var label_2="From";
var label_3="Arrival";
var header="Origin";
if(direction==INWARD)
{
localStorage.direction=INWARD;
   label_1="ETA";
   label_2="From";
   label_3="Arrival";
   header="Origin"
}
else
{
localStorage.direction=OUTWARD;
 label_1="ETD";
  label_2="To";
   label_3="Departure";
   header="Destination"
}


var data=jQuery.parseJSON(text);

var cities=[];
var arrivals=[];
var dCities=[];
var dArrivals=[];
var all_local="";
var all_abroad="";
$("#listTitle").text(label_3);

                         $("ul#arrival-board").html("");
 $("ul#arrival-domestic").html("");

                        if(data.flights.length>0)
			{
                       
globals = data.flights;

			for(var i=0;i<data.flights.length;i++)
			{
			
			
			
			var flight=data.flights[i];
			
			
			
			
			
                                 var newList='<li>'+
					'<a href="#detail" data-transition="slide" onclick="javascript:setValuesToForm('+i+',\''+header+'\');">'+
						'<h2>'+flight.origin+'</h2>'+
						'<p><strong>'+flight.flightNo+'</strong></p>'+
						'<p>'+flight.status+'</p>'+
						'<p class="ui-li-aside">'+label_1+':<strong>'+flight.arrival+'</strong></p>'+
					'</a></li>';
					
					if(flight.routeType=="D")
					{
					  flightUtilPut(dCities,dArrivals,flight.origin,newList);
					}
					else{
					   flightUtilPut(cities,arrivals,flight.origin,newList);
					}
			
			}}					
			for(var j=0;j<cities.length;j++){
			     //  $( "ul#arrival-board" ).append( ' <li data-role="list-divider">'+label_2+' '+cities[j]+' </li>');
			       all_abroad=all_abroad+ ' <li data-role="list-divider">'+label_2+' '+cities[j]+' <span style="float:right">'+data.date+'<span></li>';
			     
					for(var k=0;k<arrivals[j].schedules.length;k++)
					{
						//$( "ul#arrival-board" )
							// Append the new rows to the body
							//.append(arrivals[j].schedules[k]);
					          all_abroad=all_abroad+arrivals[j].schedules[k];
					}

			}
			
			for(var j=0;j<dCities.length;j++){
			     //  $( "ul#arrival-domestic" ).append( ' <li data-role="list-divider">From '+dCities[j]+' </li>');
			       all_local=all_local+ ' <li data-role="list-divider">From '+dCities[j]+' </li>';
			     
					for(var k=0;k<dArrivals[j].schedules.length;k++)
					{
						//$( "ul#arrival-domestic" )
							// Append the new rows to the body
							//.append(dArrivals[j].schedules[k]);
					       all_local=all_local+dArrivals[j].schedules[k];
					}

			}
			$( "ul#arrival-board" ).append(all_abroad);
			$( "ul#arrival-domestic" ).append(all_local);
			
                                              $('ul#arrival-board').listview('refresh');
                                              $('ul#arrival-domestic').listview('refresh');
					// Call the refresh method
					$( "table#table-reflow tbody" ).closest( "table#table-reflow" )
					.table( "refresh" )
					// Trigger if the new injected markup contain links or buttons that need to be enhanced
					.trigger( "create" );
	

}      


$(document ).on( "pageinit", "#track", function() {

});

$(document ).on( "pageshow", "#arrival", function() {
  $('#radio-choice-d')
          .attr('checked',true);
          $('#radio-choice-d').checkboxradio("refresh");
$('#tomorrow').text(localStorage.tomorrow);
$('#yesterday').text(localStorage.yesterday);
     $("ul#arrival-board").html("");
 $("ul#arrival-domestic").html("");

});
$(document ).on( "pageinit", "#arrival", function() {
$('#anc2').html=localStorage.anc2;
	
	$( document ).on( "click", "#add_and_refresh", function () {
					
					doPost("http://code.whereismyanmar.net/incoming.php",INWARD);
					
	});	

$( "input[name='choice-day']").click(  function (e) {
					
					callBack($(this).val());
					
	});	
	
	$( document ).on( "pageshow", "#arrival", function () {
				
if("ORG"==localStorage.query.substring(0,3))
{
  $("#listTitle").text("Arrival");
}
else
{
  $("#listTitle").text("Departure");
}


              callBack("today");
					
	});
	
	 $( document ).on( "swiperight", "#detail1", function() {
	            $.mobile.changePage( "#arrival", { transition: "slide", reverse: true } );
	  });
	


});

function callBack(day)
{
					$.mobile.showPageLoadingMsg("b", "Please wait...");
$.getJSON( "http://code.whereismyanmar.net/query.php",{"keyword":localStorage.query,"history":day})
.done(function( data) {
processMovieTypes(JSON.stringify(data),data.direction);	
  $.mobile.hidePageLoadingMsg();		
})
.fail(function( jqxhr, textStatus, error ) {
 alert(error);
});


}

function refresh(day)
{
					$.mobile.showPageLoadingMsg("b", "Please wait...");
$.getJSON( "http://code.whereismyanmar.net/query.php",{"keyword":localStorage.query,"history":day})
.done(function( data) {
 $.mobile.hidePageLoadingMsg();	
processMovieTypes(JSON.stringify(data),data.direction);	

 $("#flight_d").text(globals[selected].flightNo);
$("#flight_d").text(globals[selected].flightNo);
$("#origin_d").text(globals[selected].origin);
$("#arrival_d").text(globals[selected].arrival);
$("#status_d").html(globals[selected].status);
$("#detailHeader").html(globals[selected].flightNo);
//$("#header_1_d").text(header);


localStorage.flightNumber=globals[selected].flightNo;

//$("#positionMap").html("");
$.getJSON( "http://code.whereismyanmar.net/map/",{"flight":localStorage.flightNumber,"reverse":localStorage.direction})
.done(function(data) {
if(data.TrackLogResult!=undefined){
var logs=data.TrackLogResult.positions;
flightPlanCoordinates = [];

var logs=data.TrackLogResult.positions;


 for(var i=0;i<logs.length;i++)
{
   flightPlanCoordinates.push(new google.maps.LatLng(logs[i].latitude,logs[i].longitude));
} 
 

loadGoogleMap(flightPlanCoordinates,data);


}

 	
})
.fail(function( jqxhr, textStatus, error ) {
 alert(error);
});

});
}



$(document ).on( "pageload", "#detail", function() {

	

});

$(document ).on( "pageshow", "#detail", function() {
 $('#mapcontainer').height('0px');
 $('#positionMap').height('0px');


});

$(document ).on( "pageinit", "#detail", function() {

		$( "#load").bind( "click", function (event,ui) {
						
				         event.stopImmediatePropagation();
		                         event.preventDefault();
		
		                      $.mobile.changePage( "viewmap.htm", { transition: "slideup"} );
		
		
						// We disable the button to make clear that in this demo we have only one set of rows to inject	
						
					});
		
		$("#refresh").bind( "click", function (event,ui) {
						
				      refresh("today");

						
					});


		 $( document ).on( "swiperight", "#detail1", function() {
		
		            $.mobile.changePage( "#arrival", { transition: "slide", reverse: true } );
		        });
		


});



$( document ).on( "pageinit", "#foo", function() {


		$( "#btnDeparture" ).bind( "click", function(event, ui) {
		 getList(event,OUTWARD);
		});
		
		$( "#btnArrival" ).bind("click", function(event, ui) {
		    getList(event,INWARD);
		});
});


function getList(event,direction)
{


                  event.stopImmediatePropagation();
		  event.preventDefault();
		  $.mobile.loadPage( "#arrival", { showLoadMsg: false } );
		  var text;  
		    if(direction==INWARD)
		    {
localStorage.direction=INWARD;
		    text=localStorage.arrivals;	   
		    doPost("http://code.whereismyanmar.net/incoming.php",INWARD);
		   }
		   else if(direction==OUTWARD)
		   {
localStorage.direction=OUTWARD;
		    text=localStorage.departures;	   
		    doPost("http://code.whereismyanmar.net/outgoing.php",OUTWARD);  
		   }
		   if(text==undefined)
		   {
		     return false;
		   
		   } 
		  
		   processMovieTypes(text,direction);
		   $.mobile.changePage( "#arrival", { transition: "none"} );



}
